<?php

namespace app\index\model;
use think\Db;
use think\Model;
use think\Session;

class CartModel extends Model
{
    public function gotobuy()
    {
        if(empty(session::get('userid'))){
           $userid = $_COOKIE['userid'];
       }else{
           $userid = session::get('userid');
       }
        // $userid = 6;
       // var_dump($_POST);die;
        $data = Db::table('goods')->field('name, price')->where('id', $_POST['id'])->find();
       // var_dump($data);die;
//        $reu = Db::table('cart') ->field('count') ->where([ 'goodsid'=>$_POST['id'], 'userid'=>$userid ]) ->select();
        $reu = Db::table('cart') ->field('count') ->where([ 'goodsid'=>$_POST['id'], 'userid'=>$userid ]) ->find();

//        $data['userid'] = $_SESSION['userid'];
//        var_dump($reu);die;

        $data['userid'] = $userid;
        $data['goodsname'] = $data['name'];
        unset($data['name']);
        $data['goodsid'] = $_POST['id'];
        $data['id'] = $data['userid'];
//        var_dump($reu['count']);die;
        if( !empty($reu['count'])){
//            $data['count'] = $reu['count'] + $_POST['count'];
            $reu['count']++;
            $data['count'] = $reu['count'];
//            var_dump($data);die;
            $res = Db::table('cart') ->where('userid',$userid) ->update($data);
        }else{
//            var_dump($data);die;
            $data['count'] = 1;
            $res = Db::table('cart') ->where('userid',$userid) ->insert($data);
        }
       // var_dump($data);die;

        return $res;
    }

    public function cartmess()
    {
        if(empty(session::get('userid'))){
           $userid = $_COOKIE['userid'];
       }else{
           $userid = session::get('userid');
       }

        // $userid = 6;
        $res = Db::table('cart') ->field('*') ->where('id',$userid) ->select();
        $cid = Db::table('cart')->field('cart.goodsid')->where('cart.userid',$userid)->select();
       // var_dump(count($cid));die;
        if(!empty($cid)){
            for($a=0; $a<count($cid); $a++){
                $ppic = Db::table('goods') ->field('pictrue') ->where('id',$cid[$a]['goodsid']) ->select();
                $pic[$a] = $ppic[0];
                // var_dump($pic[$a]);
            }
                   // var_dump($this->getLastsql());
            // var_dump($pic);die;
            // echo 111;die;
            for($b=0; $b<count($pic); $b++){
                $res[$b]['pictrue'] = $pic[$b]['pictrue'];
            }
        }else{
            $res = false;
        }

       // var_dump($res);die;
       // echo 111;die;
        return $res;
    }

    public function del($id)
    {
        if(empty(session::get('userid'))){
           $userid = $_COOKIE['userid'];
       }else{
           $userid = session::get('userid');
       }
        // $userid = 6;
        $data = Db::table('cart') ->where(['goodsid'=>$id, 'userid'=>$userid]) ->delete();
//        var_dump($data);die;
        return $data;
    }

}








